package com.czwj.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.czwj.annotation.SystemControllerLog;
import com.czwj.entities.BudgetMain;
import com.czwj.entities.BudgetSubItem;
import com.czwj.entities.DataGridData;
import com.czwj.entities.Form;
import com.czwj.entities.OperateResult;
import com.czwj.entities.PageBean;
import com.czwj.entities.ProjectItem;
import com.czwj.entities.UserInfo;
import com.czwj.service.BudgetMainService;
import com.czwj.service.FormService;
import com.czwj.service.ProjectItemService;
import com.czwj.util.GsonUtil;
import com.czwj.util.TextUtil;
import com.czwj.util.WechatUtil;

import net.sf.json.JSONObject;

@Controller
public class BudgetMainAction {
	@Resource
	BudgetMainService budgetMainService;
	
	@Resource
	ProjectItemService projectItemService;
	@Resource
	FormService formService;
	
	@Value("${review_model_code}")
	private String model_code;
	
	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分");

	@RequestMapping(value = "/mainbudget.do", method = RequestMethod.GET)
	@ResponseBody
	public DataGridData<BudgetMain> budgetMain(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows,
			@RequestParam(value = "status", required = false) String status,
			@RequestParam(value = "projectitemid", required = false) String projectitemid) {
		DataGridData<BudgetMain> result = new DataGridData();
		Map<String, Object> map = new HashMap<String, Object>();
		PageBean pageBean = null;
		if (TextUtil.isNotEmpty(page) && TextUtil.isNotEmpty(rows)) {
			pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		}
		if (pageBean != null) {
			map.put("start", pageBean.getStart());
			map.put("size", pageBean.getPageSize());
		}
		Subject currentUser = SecurityUtils.getSubject();
		UserInfo userInfo = (UserInfo)currentUser.getSession().getAttribute("userInfo");
		map.put("userid", userInfo.getId());
		int roleid = userInfo.getRoleid();
		if(roleid ==1){
			result.setRows(budgetMainService.searchbylevel0(map));
			result.setTotal(budgetMainService.countbylevel0(map));
		}
		if(roleid ==2){
			result.setRows(budgetMainService.searchbylevel1(map));
			result.setTotal(budgetMainService.countbylevel1(map));
		}
		if(roleid==3){
			result.setRows(budgetMainService.searchbylevel2(map));
			result.setTotal(budgetMainService.countbylevel2(map));
		}
		if(roleid==4){
			result.setRows(budgetMainService.searchbylevel3(map));
			result.setTotal(budgetMainService.countbylevel3(map));
		}
		if(TextUtil.isNotEmpty(status)){
			map.put("status", status);
		}
		if(TextUtil.isNotEmpty(projectitemid)&&!projectitemid.equals("0")){
			map.put("projectitemid", projectitemid);
		}

		return result;
	}

	@RequestMapping(value = "/budgetMainlist", method = RequestMethod.POST)
	@ResponseBody
	public List<BudgetMain> budgetMainlist() {
		List<BudgetMain> list = budgetMainService.searchbylevel3(null);
		return list;
	}
	
	@RequestMapping(value = "defaultBudgetMainName", method = RequestMethod.GET)
	@ResponseBody
	public void defaultBudgetMainName(@RequestParam(value = "id", required = true) int id,HttpServletResponse response) throws IOException{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("projectitemid",id);
		int cnt = budgetMainService.searchbyprojectitem(map).size();
		GsonUtil.toJson(response, TextUtil.toChinese((cnt+1)+""));
	}

	@SystemControllerLog(description = "修改主预算") 
	@RequestMapping(value = "/budgetMainSave.do", method = RequestMethod.POST)
	@ResponseBody
	public OperateResult budgetMainSave(@RequestBody BudgetMain budgetMain, HttpServletRequest request)//废止
			throws Exception {
		OperateResult result = new OperateResult();
		int count = 0;
		if (budgetMain.getId() != null && budgetMain.getId() > 0) {
			count = budgetMainService.update(budgetMain);
		} else {
			Subject currentUser = SecurityUtils.getSubject();
			budgetMain.setCreaterid(((UserInfo) currentUser.getSession().getAttribute("userInfo")).getId());
			budgetMain.setCreatedate(new Date());
			budgetMain.setCreateip(request.getRemoteAddr());
			budgetMain.setStatus(6);
			count = budgetMainService.insert(budgetMain);
		}
		ProjectItem projectItem = projectItemService.selectByPrimaryKey(budgetMain.getProjectitemid());
		for (UserInfo user : projectItem.getLevel2()) {
			JSONObject data = WechatUtil.setReviewData(projectItem.getName()+" 主预算", sdf2.format(new Date()));
			sendReview(user, data);
		}
		result.setSuccess(count > 0);
		return result;
	}

	@SystemControllerLog(description = "删除主预算") 
	@RequestMapping(value = "budgetMainDelete.do", method = RequestMethod.POST)
	@ResponseBody
	public OperateResult deleteBudgetMain(@RequestParam("budgetMainid") int id) {//废止
		OperateResult result = new OperateResult();
		try {
			int count = budgetMainService.updateStatus(id);
			result.setSuccess(count > 0);
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.setSuccess(false);
			return result;
		}
	}

	private void sendReview(UserInfo userInfo,JSONObject data){
		List<Form> forms = formService.findbyuser(userInfo.getId());
		for (Form form : forms) {
			String code = WechatUtil.pushMessage(userInfo.getOpenid(), model_code, form.getFormid(),data);
			formService.deleteByPrimaryKey(form.getId());
			if(code.trim().equals("0")){
				return;
			}
		}
	}

	@RequestMapping(value = "budgetmian/searchbyprojectitemid", method = RequestMethod.GET)
	@ResponseBody
	public BudgetMain searchbyprojectitemid(@RequestParam("projectitemid") int id){
		BudgetMain budgetSubItem = budgetMainService.searchbyprojectitemid(id);
		return budgetSubItem;
	}
	@RequestMapping(value = "budgetmian/searchbyprojectitemchild", method = RequestMethod.GET)
	@ResponseBody
	public BudgetMain searchbyprojectitemchild(@RequestParam("projectitemchildid") int id){
		BudgetMain budgetSubItem = budgetMainService.searchbyprojectitemchild(id);
		return budgetSubItem;
	}
}
